package com.general.framework.zzyy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.zzyy.HandlerStrategy;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class StrategyFactory implements ApplicationContextAware {
    private static Map<Integer, HandlerStrategy> strategies;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, HandlerStrategy> map = applicationContext.getBeansOfType(HandlerStrategy.class);
        strategies = new HashMap<>();
        map.forEach((key, value) -> strategies.put(value.getType(), value));
        System.out.println(strategies); // 打印策略集合
    }

    public static HandlerStrategy getStrategy(int type) {
        return strategies.get(type);
        // 或者抛出一个自定义异常，比如：
        // throw new StrategyNotFoundException("策略不存在，类型: " + type);
    }
}